package com.xxl.job.admin.core.util;

import com.sun.jmx.snmp.Timestamp;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class SystemClockJava {

    private final long period;
    private final int corePoolSize;

    private final AtomicLong now;

    private SystemClockJava(long period, int corePoolSize) {
        this.period = period;
        this.corePoolSize = corePoolSize;
        this.now = new AtomicLong(System.currentTimeMillis());
        scheduleClockUpdating();
    }

    private static SystemClockJava instance() {
        return InstanceHolder.INSTANCE;
    }

    public static long now() {
        return instance().currentTimeMillis();
    }

    public static String nowDate() {
        return new Timestamp(now()).toString();
    }

    private void scheduleClockUpdating() {

        ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(corePoolSize, r -> {
            Thread thread = new Thread(r, "System Clock");
            thread.setDaemon(true);
            return thread;
        });
        now.set(System.currentTimeMillis());
        scheduler.scheduleAtFixedRate(now::incrementAndGet, period, period, TimeUnit.MILLISECONDS);
    }

    private long currentTimeMillis() {
        return now.get();
    }

    private static class InstanceHolder {
        public static final SystemClockJava INSTANCE = new SystemClockJava(1L, 1);
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for (long i = 0; i < Integer.MAX_VALUE; i++) {
            SystemClock.INSTANCE.currentTimeMillis();
            if (i / 10000000 == 0) {
                try {
                    TimeUnit.MILLISECONDS.sleep(2000);
                } catch (InterruptedException e) {

                }
                System.err.println(SystemClock.INSTANCE.currentTimeMillis() / 1000);
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("SystemClock Time:" + (end - start) + "毫秒");

        long start2 = System.currentTimeMillis();
        for (long i = 0; i < Integer.MAX_VALUE; i++) {
            SystemClockJava.now();
        }
        long end2 = System.currentTimeMillis();
        System.out.println("SystemClockJava Time:" + (end2 - start2) + "毫秒");

        long start3 = System.currentTimeMillis();
        for (long i = 0; i < Integer.MAX_VALUE; i++) {
            System.currentTimeMillis();
        }
        long end3 = System.currentTimeMillis();
        System.out.println("currentTimeMillis Time:" + (end3 - start3) + "毫秒");
    }
}
